/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.unisinos.simcop.builder.gui;

import br.unisinos.simcop.Utils;
import br.unisinos.simcop.core.process.SimcopTask;
import br.unisinos.simcop.data.model.ContextSequence;
import br.unisinos.simcop.data.model.Entity;
import br.unisinos.simcop.data.source.ISequenceSource;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import javax.swing.event.ListDataListener;

/**
 *
 * @author tiago
 */
public class LoadEntities extends javax.swing.JDialog {

    private EditConfigStore storeWindow;
    private SimcopTask selectSource;
    private List<Entity> entities;
    private Entity entityClicked;
    private Entity selected;

    /**
     * Creates new form LoadEntities
     */
    public LoadEntities(java.awt.Frame parent, boolean modal, EditConfigStore storeWindow) {
        super(parent, modal);
        initComponents();
        this.storeWindow = storeWindow;
        loadSources();
        Dimension d = new Dimension(800, 380);
        setPreferredSize(d);
        setMinimumSize(d);
        setSize(d);
        setLocationRelativeTo(null);
    }

    private void loadSources() {
        cbSources.setModel(new ComboBoxModel());
        cbSources.updateUI();
        btConfirm.setEnabled(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        btConfirm = new javax.swing.JButton();
        btCancel = new javax.swing.JButton();
        lbSelected = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        cbSources = new javax.swing.JComboBox();
        btLoadEntities = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        edEntitiesParameters = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        pnlTestSequenceA = new javax.swing.JPanel();
        jScrollPane7 = new javax.swing.JScrollPane();
        tabSelectEntities = new javax.swing.JTable();
        lbEntities = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Select Context Sequence");
        setPreferredSize(new java.awt.Dimension(500, 380));

        jPanel1.setPreferredSize(new java.awt.Dimension(481, 50));

        btConfirm.setText("Confirm");
        btConfirm.setEnabled(false);
        btConfirm.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btConfirmActionPerformed(evt);
            }
        });

        btCancel.setText("Cancel");
        btCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelActionPerformed(evt);
            }
        });

        lbSelected.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
        lbSelected.setText("Entity Selected:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(288, 288, 288)
                        .addComponent(btConfirm)
                        .addGap(26, 26, 26)
                        .addComponent(btCancel))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lbSelected, javax.swing.GroupLayout.PREFERRED_SIZE, 758, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(20, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(lbSelected)
                .addGap(7, 7, 7)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btConfirm)
                    .addComponent(btCancel))
                .addContainerGap(53, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_END);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("1. Select Source"));
        jPanel2.setPreferredSize(new java.awt.Dimension(534, 90));
        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        cbSources.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
        cbSources.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jPanel2.add(cbSources, new org.netbeans.lib.awtextra.AbsoluteConstraints(99, 16, 531, -1));

        btLoadEntities.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
        btLoadEntities.setText("Load Entities");
        btLoadEntities.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btLoadEntitiesActionPerformed(evt);
            }
        });
        jPanel2.add(btLoadEntities, new org.netbeans.lib.awtextra.AbsoluteConstraints(620, 50, -1, -1));

        jLabel1.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
        jLabel1.setText("Source Task:");
        jPanel2.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(6, 21, -1, -1));
        jPanel2.add(edEntitiesParameters, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 50, 435, 37));

        jLabel2.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
        jLabel2.setText("Entities Query Parameters:");
        jPanel2.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(5, 51, -1, -1));

        getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_START);

        pnlTestSequenceA.setBorder(javax.swing.BorderFactory.createTitledBorder("2. Select Entity"));
        pnlTestSequenceA.setPreferredSize(new java.awt.Dimension(371, 219));
        pnlTestSequenceA.setLayout(new java.awt.BorderLayout());

        tabSelectEntities.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null}
            },
            new String [] {
                "UID", "Name"
            }
        ));
        tabSelectEntities.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        tabSelectEntities.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabSelectEntitiesMouseClicked(evt);
            }
        });
        jScrollPane7.setViewportView(tabSelectEntities);

        pnlTestSequenceA.add(jScrollPane7, java.awt.BorderLayout.CENTER);

        lbEntities.setFont(new java.awt.Font("Dialog", 2, 12)); // NOI18N
        lbEntities.setText("0 entities found");
        lbEntities.setPreferredSize(new java.awt.Dimension(140, 15));
        pnlTestSequenceA.add(lbEntities, java.awt.BorderLayout.PAGE_END);

        getContentPane().add(pnlTestSequenceA, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tabSelectEntitiesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabSelectEntitiesMouseClicked
        btConfirm.setEnabled(false);
        entityClicked = null;
        if (entities != null && !entities.isEmpty()) {
            int idx = tabSelectEntities.getSelectedRow();
            if (idx >= 0 && idx < entities.size()) {
                entityClicked = entities.get(idx);
            }
        }
        if (entityClicked != null) {
            btConfirm.setEnabled(true);
            lbSelected.setText("Entity Selected: " + entityClicked.getName());
        }

    }//GEN-LAST:event_tabSelectEntitiesMouseClicked

    private void btLoadEntitiesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLoadEntitiesActionPerformed
        //get the selected source
        selectSource = null;
        btConfirm.setEnabled(false);
        entities = null;
        int idx = cbSources.getSelectedIndex();
        if (idx >= 0 && idx < storeWindow.getSources().size()) {
            selectSource = storeWindow.getSources().get(idx);
        }

        //load entities stored in the source        
        if (selectSource != null) {
            ISequenceSource source = null;
            StringBuilder sb = new StringBuilder();
            entities = new ArrayList<Entity>();
            try {
                source = (ISequenceSource) selectSource.createInstance();
                if (source.connectToSource()) {
                    String[] parameters = null;
                    if (!Utils.isEmpty(edEntitiesParameters.getText())) {
                        parameters = edEntitiesParameters.getText().split(";");
                    }
                    entities = source.getListEntities(parameters);
                    source.disconnectFromSource();
                } else {
                    source = null;
                    sb.append("Cannot Connect: \n");
                    for (String error : source.getErrors()) {
                        sb.append("\t").append(error).append("\n");
                    }
                }
            } catch (Exception e) {
                Utils.log(e);
                sb.append(e.getMessage());
                for (String error : source.getErrors()) {
                    sb.append("\t").append(error).append("\n");
                }
                source = null;
            }
            if (entities != null) {
                lbEntities.setText(entities.size() + " Entities Found");
            } else {
                lbEntities.setText(" {null} Entities Found");
            }
            if (source != null) {
                tabSelectEntities.setModel(new EntitiesModel(entities));
                tabSelectEntities.getColumnModel().getColumn(0).setPreferredWidth(75);
                tabSelectEntities.getColumnModel().getColumn(1).setPreferredWidth(300);
                tabSelectEntities.updateUI();
            } else {
                sb.append("\nCannot initialize source instance. Parameters:\n");
                for (String pk : selectSource.getParameters().keySet()) {
                    sb.append("\t").append(pk).append("=\"").append(selectSource.getParameters().get(pk)).append("\"\n");
                }
                LongMessage dialog = new LongMessage(new javax.swing.JFrame(), "Select Entity", sb.toString());
                dialog.setVisible(true);
            }
        }
    }//GEN-LAST:event_btLoadEntitiesActionPerformed

    private void btCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelActionPerformed
        selected = null;
        dispose();
    }//GEN-LAST:event_btCancelActionPerformed

    private void btConfirmActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btConfirmActionPerformed
        //load Sequence of Contexts
        if (selectSource != null && entityClicked != null) {
            try {
                ISequenceSource source = (ISequenceSource) selectSource.createInstance();
                if (source.connectToSource()) {
                    this.selected = source.loadEntityAndSequence(entityClicked.getUid());                    
                    dispose();
                } else {
                    source = null;
                    LongMessage dialog = new LongMessage(new javax.swing.JFrame(), "Select Entity", "Cannot connect to source");
                    dialog.setVisible(true);

                }
            } catch (Exception e) {
                Utils.log(e);
                LongMessage dialog = new LongMessage(new javax.swing.JFrame(), "Select Entity", "Error connecting to source: " + e.getMessage());
                dialog.setVisible(true);
            }

        }

    }//GEN-LAST:event_btConfirmActionPerformed

    public Entity getSelected() {
        return selected;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btCancel;
    private javax.swing.JButton btConfirm;
    private javax.swing.JButton btLoadEntities;
    private javax.swing.JComboBox cbSources;
    private javax.swing.JTextField edEntitiesParameters;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane7;
    private javax.swing.JLabel lbEntities;
    private javax.swing.JLabel lbSelected;
    private javax.swing.JPanel pnlTestSequenceA;
    private javax.swing.JTable tabSelectEntities;
    // End of variables declaration//GEN-END:variables

    class ComboBoxModel implements javax.swing.ComboBoxModel {

        private String selected;

        public void setSelectedItem(Object anItem) {
            this.selected = (String) anItem;
        }

        public Object getSelectedItem() {
            return selected;
        }

        public int getSize() {
            return storeWindow.getSources().size();
        }

        public Object getElementAt(int index) {
            return storeWindow.getSources().get(index).getLabel();
        }

        public void addListDataListener(ListDataListener l) {
        }

        public void removeListDataListener(ListDataListener l) {
        }
    }
}
